package com.yunkeji.utils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class UploadSSH {

    public static void main(String[] args) {
        String host = "121.199.59.123";
        int port = 2202;
        String user = "root";
        String password = "fanson"; // 或使用私钥认证
        String remoteDir = "/mnt";
        String localFile = "D:\\project\\aidong\\yunkeji-api\\target\\yunkeji";

        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(user, host, port);
            session.setPassword(password);

            // 跳过主机密钥检查（不推荐在生产环境中使用）
            session.setConfig("StrictHostKeyChecking", "no");

            session.connect();

            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            try (FileInputStream fis = new FileInputStream(localFile)) {
                channelSftp.put(
                        fis, remoteDir + "/" + localFile.substring(localFile.lastIndexOf('/') + 1));
                System.out.println("File uploaded successfully");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
